<template>
  <el-card class="page-container">
    <template #header>
      <div class="header">
        <span>教师</span>
        <el-input 
          v-model="searchQuery" 
          placeholder="搜索教师用户名或姓名" 
          style="width: 200px; margin-right: 10px;" 
        />
        <div class="extra">
          <el-button @click="clearForm" type="primary">添加教师</el-button>
          <el-button 
            :disabled="selectedTeachers.length === 0" 
            @click="deleteSelectedTeachers" 
            type="danger"
          >
            批量删除
          </el-button>
        </div>
      </div>
    </template>

    <!-- 添加教师弹窗 -->
    <el-dialog v-model="dialogVisible" :title="title" width="30%">
      <el-form :model="teacherModel" :rules="rules" ref="formRef" label-width="100px" style="padding-right: 30px">
        <el-form-item label="教师用户" prop="username">
          <el-input v-model="teacherModel.username" minlength="1" maxlength="10"></el-input>
        </el-form-item>
        <el-form-item label="教师姓名" prop="name">
          <el-input v-model="teacherModel.name" minlength="2" maxlength="6"></el-input>
        </el-form-item>
        <el-form-item label="邮箱" prop="email">
          <el-input v-model="teacherModel.email"></el-input>
        </el-form-item>
        <el-form-item label="手机" prop="phone">
          <el-input v-model="teacherModel.phone"></el-input>
        </el-form-item>
        <el-form-item label="职称" prop="title">
          <el-input v-model="teacherModel.title"></el-input>
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="dialogVisible = false">取消</el-button>
          <el-button type="primary" @click="title == '添加教师' ? addTeacher() : editTeacher()">
            确认
          </el-button>
        </span>
      </template>
    </el-dialog>

    <!-- 列表 -->
    <el-table 
      :data="paginatedTeachers" 
      style="width: 100%" 
      @selection-change="handleSelectionChange"
    >
      <el-table-column type="selection"></el-table-column>
      <el-table-column label="序号" width="80" type="index"> </el-table-column>
      <el-table-column label="教师用户" prop="username"></el-table-column>
      <el-table-column label="姓名" prop="name"></el-table-column>
      <el-table-column label="邮箱" prop="email"></el-table-column>
      <el-table-column label="手机" prop="phone"></el-table-column>
      <el-table-column label="职称" prop="title"></el-table-column>
      <el-table-column label="操作" width="150">
        <template #default="{ row }">
          <el-button :icon="Edit" circle plain type="primary" @click="showTeacher(row)"></el-button>
          <el-button :icon="Delete" circle plain type="danger" @click="deleteTeacher(row)"></el-button>
        </template>
      </el-table-column>
      <template #empty>
        <el-empty description="没有数据" />
      </template>
    </el-table>

    <!-- 分页 -->
    <el-pagination
      background
      :current-page="currentPage"
      :page-size="pageSize"
      @current-change="handlePageChange"
      :total="filteredTeachers.length"
      style="margin-top: 20px;">
    </el-pagination>
  </el-card>
</template>

<script setup>
import { Edit, Delete } from '@element-plus/icons-vue';
import { ref, computed } from 'vue';
import { ElMessage, ElMessageBox } from 'element-plus';
import {
  getTeacherService,
  addTeacherService,
  updateTeacherService,
  deleteService,
} from '../../api/teacher';

const searchQuery = ref(''); // 搜索条件

const teachers = ref([]);

// 计算出匹配搜索条件的教师列表
const filteredTeachers = computed(() => {
  return teachers.value.filter(teacher =>
    teacher.username.includes(searchQuery.value) ||
    teacher.name.includes(searchQuery.value)
  );
});

// 计算分页后的教师数据
const currentPage = ref(1);
const pageSize = ref(10); // 每页显示的教师数

const paginatedTeachers = computed(() => {
  const start = (currentPage.value - 1) * pageSize.value;
  return filteredTeachers.value.slice(start, start + pageSize.value);
});

// 弹框标题
const title = ref('');
// 控制添加教师弹窗
const dialogVisible = ref(false);
// 教师表单模型
const teacherModel = ref({
  username: '',
  name: '',
  email: '',
  phone: '',
  title: '',
  id: 0,
});
// 表单校验引用
const formRef = ref(null);

// 添加教师表单校验规则
const rules = {
  username: [
    { required: true, message: '请输入教师名称', trigger: 'blur' },
    { min: 1, max: 10, message: '长度在 1 到 10 个字符', trigger: 'blur' }
  ],
  name: [
    { required: true, message: '请输入教师姓名', trigger: 'blur' },
    { min: 2, max: 6, message: '长度在 2 到 6 个字符', trigger: 'blur' }
  ],
};

// 显示教师列表信息
const teacherList = async () => {
  let res = await getTeacherService();
  teachers.value = res.data;
};

// 处理选择变化的方法
const selectedTeachers = ref([]);

const handleSelectionChange = (selection) => {
  selectedTeachers.value = selection;
};

// 批量删除选中的教师
const deleteSelectedTeachers = async () => {
  if (selectedTeachers.value.length === 0) {
    ElMessage.warning('请选择要删除的教师');
    return;
  }
  ElMessageBox.confirm('您确定要删除这些教师吗?', '注意', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning',
  })
  .then(async () => {
    for (const teacher of selectedTeachers.value) {
      await deleteService(teacher.id);
    }
    selectedTeachers.value = []; // 清空选择
    teacherList(); // 刷新教师列表
    ElMessage.success('删除成功');
  })
  .catch(() => {
    ElMessage.info('删除已取消');
  });
};

// 页码改变事件
const handlePageChange = (page) => {
  currentPage.value = page;
};

// 添加教师弹窗
const addTeacher = async () => {
  formRef.value.validate(async valid => {
    if (valid) {
      let res = await addTeacherService(teacherModel.value);
      if (res) {
        ElMessage.success(res.message ? res.message : '添加成功');
        teacherList();
        dialogVisible.value = false;
      } else {
        ElMessage.error(res.message ? res.message : '很可惜，添加失败了');
      }
    }
  });
};

// 修改是弹窗展示编辑原信息
const showTeacher = (row) => {
  dialogVisible.value = true;
  title.value = '修改教师';
  Object.assign(teacherModel.value, row);
};

// 编辑教师
const editTeacher = async () => {
  let res = await updateTeacherService(teacherModel.value);
  ElMessage.success(res.message ? res.message : '修改成功!');
  teacherList();
  dialogVisible.value = false;
};

// 添加时清空表单数据
const clearForm = () => {
  dialogVisible.value = true;
  title.value = '添加教师';
  teacherModel.value = {
    username: '',
    name: '',
    email: '',
    phone: '',
    title: '',
    id: 0,
  };
  formRef.value?.resetFields();
};

// 删除教师
const deleteTeacher = async (row) => {
  ElMessageBox.confirm('您确定要删除这个教师吗', '注意', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning',
  })
  .then(async () => {
    let res = await deleteService(row.id);
    teacherList();
    dialogVisible.value = false;
    ElMessage({
      type: 'success',
      message: res.message ? res.message : '删除成功',
    });
  })
  .catch(() => {
    ElMessage({
      type: 'info',
      message: '删除已取消',
    });
  });
};

teacherList();
</script>

<style lang="scss" scoped>
.page-container {
  min-height: 100%;
  box-sizing: border-box;

  .header {
    display: flex;
    align-items: center;
    justify-content: space-between;
  }
}
</style>